package club.beimeng.sendEmail;

import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test1 {
    Queue<Integer> queue = new LinkedList<Integer>();
    boolean threadRunning = false;

    public void add(){
        try {
            Thread.sleep(300); // 一秒添加一个
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        int num = (int) (Math.random() *100 % 10);
        System.out.println("像队列添加" + num);
        queue.offer(num);
    }

    public void input(){
        for (int i = 0; i < 50; i++) {
            bThread bThread = new bThread();
            if (!threadRunning){
                add();
                threadRunning = true;
                new Thread(bThread,"规划线程").start();
            }else
                add();
            if (i == 10);
        }
    }

    class bThread implements Runnable{

        @Override
        public void run() {

            System.out.println("开启了规划线程" + new Date());
            solveThread solveThread = new solveThread();
            new Thread(solveThread,"1").start();
            while (true){
                int oldSize = queue.size();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (queue.size() - oldSize >= 3){
                    new Thread(solveThread,new Date().toString()).start();
                }
            }

        }
    }

    class solveThread implements Runnable{

        @Override
        public void run() {
//            ExecutorService pool = Executors.newFixedThreadPool(10);
//            pool.submit()
            Date date = new Date();
            System.out.println("开启了新线程" + date.getTime() );
            while (!queue.isEmpty()){
                synchronized (this){
                    try {
                        Thread.sleep(200); // 一秒添加一个
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("queue.poll() = " + queue.poll() + " 队列长度 " + queue.size() + "执行者" + date);
                }
            }
            System.out.println("线程结束" + date);

        }
    }

    public static void main(String[] args) {
        Test1 test1 = new Test1();
        test1.input();
    }
}
